package app.controllers;

import app.models.Book;
import app.services.BookListService;
import com.google.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.javalite.activeweb.AppController;
import org.javalite.activeweb.annotations.POST;

/**
 *
 * @author Kseniya Artsiukhova <kartsiukhova@productiveedge.com>
 */
public class BooksController extends AppController {

    private BookListService bookListService;

    public void index() {
        List<Book> books = bookListService.selectAllBooks();
        view("elements", books);
    }

    public void list() {
        String publicationTypeCode = param("publicationTypeCode");
        String genreCode = param("genreCode");

        List<Book> books = bookListService.bookListByGenreAndPublicationType(genreCode, publicationTypeCode);
        view("elements", books);
        view("genreCode", genreCode);
    }

    @POST
    public void deleteBooks() {
        Map<String, String[]> params = params();
        List<Long> deleteBookList = new ArrayList<Long>();

        for (String id : params.get("deleteBookList")) {
            deleteBookList.add(Long.parseLong(id));
        }

        bookListService.deleteBookList(deleteBookList);

        redirectToReferrer();
    }

    @POST
    public void newBook() {
        String genreCode = param("id");
        String name = param("name");
        String author = param("author");
        String numberOfPage = param("numberOfPage");
        String format = param("format");

        bookListService.addNewBook(genreCode, name, author, numberOfPage, format);

        redirectToReferrer();
    }

    @Inject(optional = false)
    public void setBookListService(BookListService bookListService) {
        this.bookListService = bookListService;
    }
}
